import { connect } from 'umi';
import { ApplyControllerContext, useApplyReducer } from '../common';
import { Form, Spin, message } from 'antd';
import { getApplyByIDService } from '../services/DetailOAServices';
import { DetailInfoTopViewOA } from './DetailInfoTopViewOA';
import { DetailInfoCenterViewOA } from './DetailInfoCenterViewOA';
import { DetailInfoBottomViewOA } from './DetailInfoBottomViewOA';
import { useEffect, useState } from 'react';
import { getColorTextLoadMap, getInvoiceCode, getPosIDs, getTenantID, getUserID, renderWaterMarkDom } from '@/utils';
import '../common/style.less';
import { ApplyManageAPI } from '../common/type';
import { CGZ_SQSTATE, DCG_SQSTATE, QC_SQSTATE, SQ_flowBusinessType } from '../common/Format';
import { SHTG_CHECKSTATE, procurementCodeCheck, setOAMessageSev } from '../../Acommon';
import { ILoadMapTypeAll } from '@/common';
import { addSourceDataServices, updatePlanStateServices, syncPDFtoOAServices } from '../services/UpdateService';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import moment from 'moment';

const DetailInfoViewOA: React.FC<ApplyManageAPI.IApplyDetailInfoView> = ({ curRes, locationProps }) => {
  const prefix = 'apply-update-'; /** 样式根名称 */
  const [applyForm] = Form.useForm(); /** 表单 */
  const { applyDispatch } = useApplyReducer(); /** 获取reducets */
  const [isState, setIsState] = useState<boolean>(false); /** 开关-决定是否触发添加实施接口 */
  const [saveOldApplyInfo, setSaveOldApplyInfo] = useState<Record<string, any>>({}); /** 保存原需求信息 */
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  /** 消息已读已办接口 */
  const { setOAMessageRun, setOAMessageLoaidng } = setOAMessageSev(() => {});

  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      // 做已读办理的接口处理
      let infoObject = res?.obj;
      if (infoObject && infoObject?.paramObject?.[SQ_flowBusinessType()]) {
        let workFlowNode = infoObject?.paramObject?.[SQ_flowBusinessType()];
        if (
          workFlowNode &&
          workFlowNode?.mactivitiTaskList?.length > 0 &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
          workFlowNode?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
        ) {
          setOAMessageRun({
            // 已读未办
            id: locationProps?.state?.taskId,
            isRemark: 0,
            viewType: 1,
          });
        }
      }
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getApplyByIDRun, getApplyByIDLoading, getApplyByIDInfo, reloadDetailInfo } = getApplyByIDService(detailsCallback);

  /** 修改计划状态,采购申请审批同意后-修改计划状态信息 执行中 */
  const { updatePlanStateRun, updatePlanStateLoading } = updatePlanStateServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
      reloadDetailInfo();
    }
  });

  /** 添加实施 */
  const { addSourceDataRun } = addSourceDataServices((res) => {
    if (res?.msgFlag) {
      message.success(res.msg);
      const params = {
        calibrateID: null,
        applyID: getApplyByIDInfo?.id,
        state: `1`,
      };
      updatePlanStateRun(params);
    }
  });

  /** 初始化 */
  useEffect(() => {
    if (locationProps?.state?.pageInfo?.id) {
      getApplyByIDRun({
        id: locationProps?.state?.pageInfo?.id,
      });
    }
  }, [locationProps?.state?.pageInfo?.id]);

  const { syncPDFtoOARun, syncPDFtoOALoading } = syncPDFtoOAServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
    }
  });
  const syncPDFtoOARunfun = (infoObj) => {
    //需要调用同步接口
    let mactivitiHisTaskInstList =
      infoObj?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1004`]?.mactivitiHisProcinstList?.[0]?.mactivitiHisTaskInstList;
    let resObj = { ...infoObj, paramObject: { mactivitiHisTaskInstList } };
    syncPDFtoOARun(resObj);
  };

  /** 监听状态添加实施 */
  useEffect(() => {
    /** 设置开关 */
    if (
      getApplyByIDInfo?.state &&
      getApplyByIDInfo?.state != DCG_SQSTATE() &&
      getApplyByIDInfo?.checkState &&
      getApplyByIDInfo?.checkState != SHTG_CHECKSTATE()
    ) {
      setIsState(true);
    }

    if (
      getApplyByIDInfo?.state &&
      getApplyByIDInfo?.state == DCG_SQSTATE() &&
      getApplyByIDInfo?.checkState &&
      getApplyByIDInfo?.checkState == SHTG_CHECKSTATE()
    ) {
      /** 判断开关，确保最后一个审批人是在采购申请审核中进入到页面 */
      if (isState) {
        let arr = [];
        arr = getApplyByIDInfo?.mpurchasePacks.map((item: any) => {
          return {
            packID: item.id,
            // 这是添加实施（招标文件编制）的接口，实施（招标文件编制）需要用来开启流程
            businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1004`, //流程类别
            workflowType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1004`, //流程类型
            state: procurementCodeCheck(item?.procureReal)
              ? `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1010` //实施状态 待实施
              : `${getTenantID()}${ILoadMapTypeAll?.CURRYOUT_STATE}1000`, //实施状态：待编制
            syncFinanceTime: procurementCodeCheck(item?.procureReal) ? moment(new Date()).format('YYYY-MM-DD HH:mm:ss') : null,
          };
        });

        const result = getApplyByIDInfo?.mpurchasePacks?.find((item) => procurementCodeCheck(item?.procureReal));
        let reqBody: Record<string, any> = {
          applyID: getApplyByIDInfo?.id,
          mpurchaseSourceList: arr,
          sourceCode: getInvoiceCode('SS'),
        };
        if (result) {
          reqBody.applyState = CGZ_SQSTATE();
        }
        addSourceDataRun({ ...reqBody });
        syncPDFtoOARunfun(getApplyByIDInfo);
      }
    }
  }, [getApplyByIDInfo?.state, getApplyByIDInfo?.checkState]);

  // 初始化水印
  // useEffect(() => {
  //   renderWaterMarkDom('applyOAPage-divBox', true);
  //   return () => {
  //     renderWaterMarkDom('applyOAPage-divBox', false);
  //   };
  // }, []);

  return (
    <ApplyControllerContext.Provider
      value={{
        styleFixCls: prefix,
        curRes,
        locationID: locationProps?.state?.id,
        applyDispatch,
        pageType: locationProps?.state?.pageType,
        delPathName: locationProps?.state?.pathname,
        oldApplyInfo: {
          ...saveOldApplyInfo,
        },
        applyForm,
        reloadDetail: reloadDetailInfo,
        applyDetailInfo: {
          ...getApplyByIDInfo,
          // supplyTypeName: getColorTextLoadMap(getApplyByIDInfo?.supplyTypeName)?.colorText,
          procureRealName: getColorTextLoadMap(getApplyByIDInfo?.procureRealName)?.colorText,
        },
        setInvalidState,
        invalidState,
        setOAMessageRun,
        taskId: locationProps?.state?.taskId,
      }}
    >
      <Spin spinning={getApplyByIDLoading || setOAMessageLoaidng || updatePlanStateLoading || syncPDFtoOALoading}>
        <div className={`${prefix}infoViewOA`} id={'applyOAPage-divBox'}>
          <DetailInfoTopViewOA />
          <DetailInfoCenterViewOA />
          <DetailInfoBottomViewOA />
        </div>
      </Spin>

      {invalidState?.isShow && (
        <RevokeModal
          resObj={invalidState?.resObj}
          revokeRequestUrl={'/purchaseApplyController/invalid'}
          onClose={() => setInvalidState({})}
          reqBody={{ state: QC_SQSTATE() }}
          modalTip={
            <div style={{ color: '#000' }}>
              确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
            </div>
          }
          reloadRequest={reloadDetailInfo}
        />
      )}
    </ApplyControllerContext.Provider>
  );
};

export default connect(({ baseLogin }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
}))(DetailInfoViewOA);
